﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Aspose.Cells;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using Senparc.CO2NET.APM;
using SHZY.BaseData.Entitys.Entity;
using SHZY.Business.Entitys;
using SHZY.Business.Entitys.Dto.customercomplaint;
using SHZY.Business.Entitys.Dto.customerfile;
using SHZY.Business.Entitys.Entity;
using SHZY.Business.Entitys.OA;
using SHZY.Business.Interfaces;
using SHZY.ClayObject;
using SHZY.Common.Configuration;
using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Security;
using SHZY.Common.Enum;
using SHZY.Common.Extension;
using SHZY.Common.Filter;
using SHZY.Common.Models;
using SHZY.Common.Models.NPOI;
using SHZY.Common.Security;
using SHZY.DataEncryption;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Message.Interfaces.Message;
using SHZY.Systems.Entitys.Permission;
using SHZY.Systems.Entitys.System;
using SHZY.Systems.Interfaces.System;
using SHZY.WorkFlow.Entitys.Model.Item;
using SqlSugar;

namespace SHZY.Business
{
    /// <summary>
    /// 业务实现：客户投诉主表.
    /// </summary>
    [ApiDescriptionSettings(Tag = "Business", Name = "QmsBusiCustomerComplaint", Order = 200)]
    [Route("api/Business/[controller]")]
    public class QmsBusiCustomerComplaintService : IQmsBusiCustomerComplaintService, IDynamicApiController, ITransient
    {
        /// <summary>
        /// 服务基础仓储.
        /// </summary>
        private readonly ISqlSugarRepository<QmsBusiCustomerComplaintEntity> _repository;
        private readonly ISqlSugarRepository<QmsBusiCustomerFileEntity> _fileRepository;

        /// <summary>
        /// 多租户事务.
        /// </summary>
        private readonly ITenant _db;

        /// <summary>
        /// 数据接口服务.
        /// </summary>
        private readonly IDataInterfaceService _dataInterfaceService;

        /// <summary>
        /// 用户管理.
        /// </summary>
        private readonly IUserManager _userManager;

        /// <summary>
        /// 单据编号服务
        /// </summary>
        private readonly IBillRullService _billRullService;
        private readonly IMessageService _messageService;

        /// <summary>
        /// 初始化一个<see cref="QmsBusiCustomerComplaintService"/>类型的新实例.
        /// </summary>
        public QmsBusiCustomerComplaintService(
            ISqlSugarRepository<QmsBusiCustomerComplaintEntity> qmsBusiCustomerComplaintRepository,
            IDataInterfaceService dataInterfaceService,
            ISqlSugarClient context,
            IBillRullService billRullService,
            IUserManager userManager, ISqlSugarRepository<QmsBusiCustomerFileEntity> fileRepository, IMessageService messageService)
        {
            _repository = qmsBusiCustomerComplaintRepository;
            _dataInterfaceService = dataInterfaceService;
            _db = context.AsTenant();
            _userManager = userManager;
            _billRullService = billRullService;
            _fileRepository = fileRepository;
            _messageService = messageService;
        }

        private static DateTime timeStampStartTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        public static DateTime LongTimeStampToDateTime(long longTimeStamp)
        {
            return timeStampStartTime.AddMilliseconds(longTimeStamp).ToLocalTime();
        }

        /// <summary>
        /// 获取客户投诉主表.
        /// </summary>
        /// <param name="id">主键值.</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            //主表信息
            var CustomerComplaintList = await _repository.Context.Queryable<QmsBusiCustomerComplaintEntity>().Where(it => it.Id == id).Select(it => new QmsBusiCustomerComplaintListOutput()
            {
                id = it.Id,
                no = it.No,
                customerNo = it.CustomerNo,
                customerName = it.CustomerName,
                feedbackStage = it.FeedbackStage,
                feedbackUserName = it.FeedbackUserName,
                feedbackDate = it.FeedbackDate,
                feedbackWay = it.FeedbackWay,
                feedbackNo = it.FeedbackNo,
                complaintType = it.ComplaintType,
                productName = it.ProductName,
                defectCategory = it.DefectCategory,
                problemDescription = it.ProblemDescription,
                checkUserId = it.CheckUserId,
                checkDate = it.CheckDate,
                checkCause = it.CheckCause,
                checkCauseOut = it.CheckCauseOut,
                checkCauseRoot = it.CheckCauseRoot,
                checkProblem = it.CheckProblem,
                checkDuplicate = it.CheckDuplicate,
                checkMajor = it.CheckMajor,
                tcProcessing = it.TcProcessing,
                tcIntercept = it.TcIntercept,
                tcPlannedDate = it.TcPlannedDate,
                tcResponsible = it.TcResponsible,
                lcPrevention = it.LcPrevention,
                lcLeakage = it.LcLeakage,
                lcPlannedDate = it.LcPlannedDate,
                lcResponsible = it.LcResponsible,
                lcActualDate = it.LcActualDate,
                lcStatus = it.LcStatus,
                qualityManager = it.QualityManager,
                qualityMaterial = it.QualityMaterial,
                qualityRework = it.QualityRework,
                qualityFreight = it.QualityFreight,
                qualityTravel = it.QualityTravel,
                qualityCDeductions = it.QualityCDeductions,
                qualityEstimated = it.QualityEstimated,
                qualityTotalAmount = it.QualityTotalAmount,
                remark = it.Remark,
                cancelUserId = it.CancelUserId,
                cancelDate = it.CancelDate,
                status = it.Status,
                creatorUserId = it.CreatorUserId,
                creatorTime = it.CreatorTime,
                qualityDept = it.QualityDept,
                qualityResponsible = it.QualityResponsible,
                checkBadNum = it.CheckBadNum,
                tcActualDate = it.TcActualDate,
                tcStatus = it.TcStatus,
                problemAttribution = it.ProblemAttribution,
            }).FirstAsync();
            //不合格图片信息
            //CustomerComplaintList.ImageList = await _repository.Context.Queryable<QmsBusiCustomerFileEntity>().Where(it => it.CustomerId == CustomerComplaintList.id && it.Type == 0).Select(it => new QmsBusiCustomerFileListOutput()
            //{
            //    id = it.Id,
            //    fileInfo = it.FileInfo,
            //    type = it.Type,
            //    remark = it.Remark
            //}).ToListAsync();
            CustomerComplaintList.ImageList = _fileRepository.AsQueryable().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.Type == 0&&it.CustomerId==id).ToList().Adapt<List<QmsBusiCustomerFileInfoOutput>>();

            ////作证资料
            CustomerComplaintList.DataList = _fileRepository.AsQueryable().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.Type == 1 && it.CustomerId == id).ToList().Adapt<List<QmsBusiCustomerFileInfoOutput>>();

            //CustomerComplaintList.DataList = await _repository.Context.Queryable<QmsBusiCustomerFileEntity>().Where(it => it.CustomerId == CustomerComplaintList.id && it.Type == 1).Select(it => new QmsBusiCustomerFileListOutput()
            //{
            //    id = it.Id,
            //    fileInfo = it.FileInfo,
            //    type = it.Type,
            //    remark = it.Remark
            //}).ToListAsync();
            return CustomerComplaintList;
        }

        /// <summary>
        /// 获取客户投诉主表列表.
        /// </summary>
        /// <param name="input">请求参数.</param>
        /// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] QmsBusiCustomerComplaintListQueryInput input)
        {
            if (!string.IsNullOrEmpty(input.feedbackDate))
            {
                string[] deliveryDate = input.feedbackDate.Split(',');
                input.feedbackDateStatus = LongTimeStampToDateTime(Convert.ToInt64(deliveryDate[0]));
                input.feedbackDateEnd = Convert.ToDateTime(LongTimeStampToDateTime(Convert.ToInt64(deliveryDate[1])).ToString("yyyy-MM-dd 23:59:59.998"));
            }
            var data = await _repository.Context.Queryable<QmsBusiCustomerComplaintEntity>()
                .Where(it => it.DeleteMark == null && it.EnabledMark == 1)
                .WhereIF(!string.IsNullOrEmpty(input.status), it => it.Status.ToString().Contains(input.status))
                .WhereIF(!string.IsNullOrEmpty(input.no), it => it.No.Contains(input.no))
                .WhereIF(!string.IsNullOrEmpty(input.customerName), it => it.CustomerName.Contains(input.customerName))
                .WhereIF(!string.IsNullOrEmpty(input.feedbackStage), it => it.FeedbackStage.Contains(input.feedbackStage))
                .WhereIF(!string.IsNullOrEmpty(input.feedbackUserName), it => it.FeedbackUserName.Contains(input.feedbackUserName))
                .WhereIF(!string.IsNullOrEmpty(input.feedbackDate), it => SqlFunc.Between(it.FeedbackDate, input.feedbackDateStatus, input.feedbackDateEnd))
                .WhereIF(!string.IsNullOrEmpty(input.feedbackWay), it => it.FeedbackWay.Contains(input.feedbackWay))
                .WhereIF(!string.IsNullOrEmpty(input.feedbackNo), it => it.FeedbackNo.Contains(input.feedbackNo))
                .WhereIF(!string.IsNullOrEmpty(input.complaintType), it => it.ComplaintType.Contains(input.complaintType))
                .WhereIF(!string.IsNullOrEmpty(input.productName), it => it.ProductName.Contains(input.productName))
                .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.No.Contains(input.keyword) || it.CustomerName.Contains(input.keyword) || it.FeedbackStage.Contains(input.keyword) || it.FeedbackUserName.Contains(input.keyword) || it.FeedbackWay.Contains(input.keyword) || it.FeedbackNo.Contains(input.keyword) || it.ComplaintType.Contains(input.keyword) || it.ProductName.Contains(input.keyword))
                .OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.Id)
                .Select(it => new QmsBusiCustomerComplaintListOutput
                {
                    id = it.Id,
                    no = it.No,
                    customerNo = it.CustomerNo,
                    customerName = it.CustomerName,
                    feedbackStage = it.FeedbackStage,
                    feedbackUserName = it.FeedbackUserName,
                    feedbackDate = it.FeedbackDate,
                    feedbackWay = it.FeedbackWay,
                    feedbackNo = it.FeedbackNo,
                    complaintType = it.ComplaintType,
                    productName = it.ProductName,
                    defectCategory = it.DefectCategory,
                    problemDescription = it.ProblemDescription,
                    checkUserId = it.CheckUserId,
                    checkDate = it.CheckDate,
                    checkCause = it.CheckCause,
                    checkCauseOut = it.CheckCauseOut,
                    checkCauseRoot = it.CheckCauseRoot,
                    checkProblem = it.CheckProblem,
                    checkDuplicate = it.CheckDuplicate,
                    checkMajor = it.CheckMajor,
                    tcProcessing = it.TcProcessing,
                    tcIntercept = it.TcIntercept,
                    tcPlannedDate = it.TcPlannedDate,
                    tcResponsible = it.TcResponsible,
                    lcPrevention = it.LcPrevention,
                    lcLeakage = it.LcLeakage,
                    lcPlannedDate = it.LcPlannedDate,
                    lcResponsible = it.LcResponsible,
                    lcActualDate = it.LcActualDate,
                    lcStatus = it.LcStatus,
                    qualityManager = it.QualityManager,
                    qualityMaterial = it.QualityMaterial,
                    qualityRework = it.QualityRework,
                    qualityFreight = it.QualityFreight,
                    qualityTravel = it.QualityTravel,
                    qualityCDeductions = it.QualityCDeductions,
                    qualityEstimated = it.QualityEstimated,
                    qualityTotalAmount = it.QualityTotalAmount,
                    remark = it.Remark,
                    cancelUserId = it.CancelUserId,
                    cancelDate = it.CancelDate,
                    status = it.Status,
                    //creatorUserId = it.CreatorUserId,
                    creatorUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.CreatorUserId).Select(p => p.RealName),
                    creatorTime = it.CreatorTime,
                    problemAttribution = it.ProblemAttribution,
                }).OrderByIF(!string.IsNullOrEmpty(input.sidx), it => input.sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
            return PageResult<QmsBusiCustomerComplaintListOutput>.SqlSugarPageResult(data);
        }

        /// <summary>
        /// 无分页列表.
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task<dynamic> GetNoPagingList([FromQuery] QmsBusiCustomerComplaintListQueryInput input)
        {
            if (!string.IsNullOrEmpty(input.feedbackDate))
            {
                string[] deliveryDate = input.feedbackDate.Split(',');
                input.feedbackDateStatus = LongTimeStampToDateTime(Convert.ToInt64(deliveryDate[0]));
                input.feedbackDateEnd = Convert.ToDateTime(LongTimeStampToDateTime(Convert.ToInt64(deliveryDate[1])).ToString("yyyy-MM-dd 23:59:59.998"));
            }
            var data = await _repository.Context.Queryable<QmsBusiCustomerComplaintEntity>()
                .Where(it => it.DeleteMark == null && it.EnabledMark == 1)
                .WhereIF(!string.IsNullOrEmpty(input.no), it => it.No.Contains(input.no))
                .WhereIF(!string.IsNullOrEmpty(input.customerName), it => it.CustomerName.Contains(input.customerName))
                .WhereIF(!string.IsNullOrEmpty(input.feedbackStage), it => it.FeedbackStage.Contains(input.feedbackStage))
                .WhereIF(!string.IsNullOrEmpty(input.feedbackUserName), it => it.FeedbackUserName.Contains(input.feedbackUserName))
                .WhereIF(!string.IsNullOrEmpty(input.feedbackDate), it => SqlFunc.Between(it.FeedbackDate, input.feedbackDateStatus, input.feedbackDateEnd))
                .WhereIF(!string.IsNullOrEmpty(input.feedbackWay), it => it.FeedbackWay.Contains(input.feedbackWay))
                .WhereIF(!string.IsNullOrEmpty(input.feedbackNo), it => it.FeedbackNo.Contains(input.feedbackNo))
                .WhereIF(!string.IsNullOrEmpty(input.complaintType), it => it.ComplaintType.Contains(input.complaintType))
                .WhereIF(!string.IsNullOrEmpty(input.productName), it => it.ProductName.Contains(input.productName))
                .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.No.Contains(input.keyword) || it.CustomerName.Contains(input.keyword) || it.FeedbackStage.Contains(input.keyword) || it.FeedbackUserName.Contains(input.keyword) || it.FeedbackWay.Contains(input.keyword) || it.FeedbackNo.Contains(input.keyword) || it.ComplaintType.Contains(input.keyword) || it.ProductName.Contains(input.keyword))
                .OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.Id)
                .Select(it => new QmsBusiCustomerComplaintListOutput
                {
                    id = it.Id,
                    no = it.No,
                    customerNo = it.CustomerNo,
                    customerName = it.CustomerName,
                    feedbackStage = it.FeedbackStage,
                    feedbackUserName = it.FeedbackUserName,
                    feedbackDate = it.FeedbackDate,
                    feedbackWay = it.FeedbackWay,
                    feedbackNo = it.FeedbackNo,
                    complaintType = it.ComplaintType,
                    productName = it.ProductName,
                    defectCategory = it.DefectCategory,
                    problemDescription = it.ProblemDescription,
                    checkUserId = it.CheckUserId,
                    checkDate = it.CheckDate,
                    checkCause = it.CheckCause,
                    checkCauseOut = it.CheckCauseOut,
                    checkCauseRoot = it.CheckCauseRoot,
                    checkProblem = it.CheckProblem,
                    checkDuplicate = it.CheckDuplicate,
                    checkMajor = it.CheckMajor,
                    tcProcessing = it.TcProcessing,
                    tcIntercept = it.TcIntercept,
                    tcPlannedDate = it.TcPlannedDate,
                    tcResponsible = it.TcResponsible,
                    lcPrevention = it.LcPrevention,
                    lcLeakage = it.LcLeakage,
                    lcPlannedDate = it.LcPlannedDate,
                    lcResponsible = it.LcResponsible,
                    lcActualDate = it.LcActualDate,
                    lcStatus = it.LcStatus,
                    qualityManager = it.QualityManager,
                    qualityMaterial = it.QualityMaterial,
                    qualityRework = it.QualityRework,
                    qualityFreight = it.QualityFreight,
                    qualityTravel = it.QualityTravel,
                    qualityCDeductions = it.QualityCDeductions,
                    qualityEstimated = it.QualityEstimated,
                    qualityTotalAmount = it.QualityTotalAmount,
                    remark = it.Remark,
                    cancelUserId = it.CancelUserId,
                    cancelDate = it.CancelDate,
                    status = it.Status,
                    creatorUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.CreatorUserId).Select(p => p.RealName),
                    creatorTime = it.CreatorTime,
                    problemAttribution = it.ProblemAttribution,
                }).ToListAsync();
            return data;
        }

        /// <summary>
        /// 导出客户投诉主表.
        /// </summary>
        /// <param name="input">请求参数.</param>
        /// <returns></returns>
        [HttpGet("Actions/Export")]
        public async Task<dynamic> Export([FromQuery] QmsBusiCustomerComplaintListQueryInput input)
        {
            var exportData = new List<QmsBusiCustomerComplaintListOutput>();
            if (input.dataType == 0)
                exportData = Clay.Object(await GetList(input)).Solidify<PageResult<QmsBusiCustomerComplaintListOutput>>().list;
            else
                exportData = await GetNoPagingList(input);
            List<ParamsModel> paramList = "[{\"value\":\"工单编号\",\"field\":\"no\"},{\"value\":\"客户编码\",\"field\":\"customerNo\"},{\"value\":\"客户名称\",\"field\":\"customerName\"},{\"value\":\"反馈阶段\",\"field\":\"feedbackStage\"},{\"value\":\"反馈人\",\"field\":\"feedbackUserName\"},{\"value\":\"反馈日期\",\"field\":\"feedbackDate\"},{\"value\":\"反馈方式\",\"field\":\"feedbackWay\"},{\"value\":\"反馈单号\",\"field\":\"feedbackNo\"},{\"value\":\"抱怨类型\",\"field\":\"complaintType\"},{\"value\":\"产品名称\",\"field\":\"productName\"},{\"value\":\"缺陷类别\",\"field\":\"defectCategory\"},{\"value\":\"问题描述\",\"field\":\"problemDescription\"},{\"value\":\"问题归属\",\"field\":\"problemAttribution\"},{\"value\":\"调查人\",\"field\":\"checkUserId\"},{\"value\":\"调查日期\",\"field\":\"checkDate\"},{\"value\":\"发生原因\",\"field\":\"checkCause\"},{\"value\":\"流出原因\",\"field\":\"checkCauseOut\"},{\"value\":\"根本原因\",\"field\":\"checkCauseRoot\"},{\"value\":\"问题类别\",\"field\":\"checkProblem\"},{\"value\":\"是否重复\",\"field\":\"checkDuplicate\"},{\"value\":\"是否重大\",\"field\":\"checkMajor\"},{\"value\":\"反馈现场的处理对策\",\"field\":\"tcProcessing\"},{\"value\":\"不良发生的拦截对策\",\"field\":\"tcIntercept\"},{\"value\":\"计划完成时间\",\"field\":\"tcPlannedDate\"},{\"value\":\"责任人\",\"field\":\"tcResponsible\"},{\"value\":\"实际完成时间\",\"field\":\"lcActualDate\"},{\"value\":\"执行状态0未关闭 1关闭\",\"field\":\"lcStatus\"},{\"value\":\"防止发生\",\"field\":\"lcPrevention\"},{\"value\":\"防止流出\",\"field\":\"lcLeakage\"},{\"value\":\"计划完成时间\",\"field\":\"lcPlannedDate\"},{\"value\":\"责任人\",\"field\":\"lcResponsible\"},{\"value\":\"责任主管\",\"field\":\"qualityManager\"},{\"value\":\"材料费\",\"field\":\"qualityMaterial\"},{\"value\":\"返工费\",\"field\":\"qualityRework\"},{\"value\":\"运输费\",\"field\":\"qualityFreight\"},{\"value\":\"差旅费\",\"field\":\"qualityTravel\"},{\"value\":\"客户扣款\",\"field\":\"qualityCDeductions\"},{\"value\":\"预估挽回损失\",\"field\":\"qualityEstimated\"},{\"value\":\"合计金额\",\"field\":\"qualityTotalAmount\"},{\"value\":\"备注\",\"field\":\"remark\"},{\"value\":\"关闭人\",\"field\":\"cancelUserId\"},{\"value\":\"关闭日期\",\"field\":\"cancelDate\"},{\"value\":\"状态\",\"field\":\"status\"},]".ToList<ParamsModel>();
            ExcelConfig excelconfig = new ExcelConfig();
            excelconfig.FileName = "客户投诉.xls";
            excelconfig.HeadFont = "微软雅黑";
            excelconfig.HeadPoint = 10;
            excelconfig.IsAllSizeColumn = true;
            excelconfig.ColumnModel = new List<ExcelColumnModel>();
            foreach (var item in input.selectKey.Split(',').ToList())
            {
                var isExist = paramList.Find(p => p.field == item);
                if (isExist != null)
                    excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
            }

            var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
            ExcelExportHelper<QmsBusiCustomerComplaintListOutput>.Export(exportData, excelconfig, addPath);
            var fileName = _userManager.UserId + "|" + addPath + "|xls";
            return new
            {
                name = excelconfig.FileName,
                url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "SHZY")
            };
        }

        /// <summary>
        /// 批量关闭工单.
        /// </summary>
        /// <param name="ids">主键数组.</param>
        /// <returns></returns>
        [HttpPost("CloseWorkOrder")]
        public async Task CloseWorkOrder([FromBody] List<string> ids)
        {
            var entitys = await _repository.Context.Queryable<QmsBusiCustomerComplaintEntity>().In(it => it.Id, ids).ToListAsync();
            if (entitys.Count > 0)
            {
                try
                {
                    // 开启事务
                    _db.BeginTran();

                    await _repository.Context.Updateable<QmsBusiCustomerComplaintEntity>().SetColumns(it => new QmsBusiCustomerComplaintEntity() { Status = 4, CancelUserId = _userManager.UserId, CancelDate = DateTime.Now }).Where(it => ids.Contains(it.Id)).ExecuteCommandAsync();

                    // 关闭事务
                    _db.CommitTran();
                }
                catch (Exception ex)
                {
                    // 回滚事务
                    _db.RollbackTran();
                    throw Oops.Oh("关闭工单失败！错误信息：" + ex);
                }
            }
        }

        /// <summary>
        /// 新建客户投诉主表.
        /// </summary>
        /// <param name="input">参数.</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] QmsBusiCustomerComplaintCrInput input)
        {
            var customercomplaintmodel = input.Adapt<QmsBUsiCustomerComplaintModel>();
            //客户投诉主表
            var CustomerComplaintEntity = input.Adapt<QmsBusiCustomerComplaintEntity>();
            CustomerComplaintEntity.Id = SnowflakeIdHelper.NextId();
            CustomerComplaintEntity.CreatorTime = DateTime.Now;
            //CustomerComplaintEntity.No = await _billRullService.GetBillNumber("workordeCode");
            //var id = CustomerComplaintEntity.Id.Copy();
            //customercomplaintmodel.Id = id;
            try
            {
                _db.BeginTran();
                //客户主表insert
                var customercomplaint = await _repository.Context.Insertable(CustomerComplaintEntity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();

                if (!(customercomplaint > 0))
                {
                    _db.RollbackTran();
                    throw Oops.Oh(ErrorCode.COM1000);
                }
                _db.CommitTran();
                var customerid = _repository.Context.Queryable<QmsBusiCustomerComplaintEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.No == input.No).Select(it => new { Id = it.Id, IsInvestigation = it.IsInvestigation, CreatorTine = it.CreatorTime, IsTemporary = it.IsTemporary, IsQuality = it.IsQuality, IsLongtime=it.IsLongtime }).First();
                customercomplaintmodel.Id = customerid.Id;
                UpdateCustomerComplaintStatus(customercomplaintmodel);
                //消息推送
                bool isLogin = true;
                CustomerComplaintEntity.CheckUserId = isLogin ? _userManager.UserId : "system";
                //发送的用户
                //根据字段判断是否第一次发送，已发送不需要再次发送
                if ((customerid.IsInvestigation == 0 || customerid.IsInvestigation == null) && !string.IsNullOrEmpty(input.CheckUserId))
                {
                    var userInfo = await _repository.Context.Queryable<UserEntity>().Where(it => it.Id == input.CheckUserId).FirstAsync();
                    JArray jArray = new JArray();
                    JObject jObject = new JObject();
                    //jObject.Add("text", "客诉-客户名称-产品名称-缺陷类别");
                    jObject.Add("text", "客诉-" + input.CustomerName + "-" + input.ProductName + "-" + input.DefectCategory);
                    jObject.Add("no", input.No);
                    jObject.Add("problemAttribution", input.ProblemAttribution);
                    jObject.Add("feedbackStage", input.FeedbackDate);
                    jObject.Add("feedbackUserName", input.FeedbackUserName);
                    jObject.Add("feedbackDate", input.FeedbackDate);
                    jObject.Add("feedbackWay", input.FeedbackWay);
                    jObject.Add("feedbackNo", input.FeedbackNo);
                    jObject.Add("complaintType", input.ComplaintType);
                    jObject.Add("problemDescription", input.ProblemDescription);
                    jObject.Add("creatorUserId", input.CreatorUserId);
                    jObject.Add("creatorTime", customerid.CreatorTine);
                    //jObject.Add("date", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    jArray.Add(jObject);
                    _messageService.AddMessageEvent("CustomerBasicInformation", userInfo.Id, jArray.ToJsonString(), null, isLogin);
                    //修改状态为已发送
                    await _repository.Context.Updateable<QmsBusiCustomerComplaintEntity>().SetColumns(it => new QmsBusiCustomerComplaintEntity { IsInvestigation = 1 }).Where(it => it.Id == customerid.Id).ExecuteCommandAsync();
                }
                //邮件2触发条件--临时对策和长期对策的责任热和计划日期不为空
                if ((customerid.IsTemporary == 0 || customerid.IsTemporary == null) && !string.IsNullOrEmpty(input.TcResponsible) && input.TcPlannedDate != null )
                {
                    //临时对策责任人
                    var TcResponsible = await _repository.Context.Queryable<UserEntity>().Where(it => it.Id == input.TcResponsible).FirstAsync();
                    //长期对策责任人
                    //var LcResponsible = await _repository.Context.Queryable<UserEntity>().Where(it => it.Id == input.LcResponsible).FirstAsync();
                    ////发送人，拼接字符串
                    //string userlist = TcResponsible.Id + "," + LcResponsible.Id;
                    JArray jArray = new JArray();
                    JObject jObject = new JObject();
                    jObject.Add("text", "客诉-" + input.CustomerName + "-" + input.ProductName + "-" + input.DefectCategory);
                    jObject.Add("no", input.No);
                    jObject.Add("problemAttribution", input.ProblemAttribution);
                    jObject.Add("feedbackStage", input.FeedbackDate);
                    jObject.Add("feedbackUserName", input.FeedbackUserName);
                    jObject.Add("feedbackDate", input.FeedbackDate);
                    jObject.Add("feedbackWay", input.FeedbackWay);
                    jObject.Add("feedbackNo", input.FeedbackNo);
                    jObject.Add("complaintType", input.ComplaintType);
                    jObject.Add("problemDescription", input.ProblemDescription);
                    jObject.Add("checkUserId", input.CheckUserId);
                    jObject.Add("checkDate", input.CheckDate);
                    jObject.Add("checkCause", input.CheckCause);
                    jObject.Add("checkCauseOut", input.CheckCauseOut);
                    jObject.Add("checkCauseRoot", input.CheckCauseRoot);
                    jObject.Add("checkProblem", input.CheckProblem);
                    jObject.Add("checkDuplicate", input.CheckDuplicate);
                    jObject.Add("checkMajor", input.CheckMajor);
                    jObject.Add("checkBadNum", input.CheckBadNum);
                    jObject.Add("creatorUserId", input.CreatorUserId);
                    jObject.Add("creatorTime", customerid.CreatorTine);
                    //jObject.Add("date", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    jArray.Add(jObject);
                    _messageService.AddMessageEvent("CustomerCountermeasure", TcResponsible.Id, jArray.ToJsonString(), null, isLogin);
                    //修改状态为已发送
                    await _repository.Context.Updateable<QmsBusiCustomerComplaintEntity>().SetColumns(it => new QmsBusiCustomerComplaintEntity { IsTemporary = 1 }).Where(it => it.Id == customerid.Id).ExecuteCommandAsync();
                }
                //邮件2触发条件长期对策责任人和计划日期不为空
                if ((customerid.IsLongtime == 0 || customerid.IsLongtime == null) && !string.IsNullOrEmpty(input.LcResponsible) && input.LcPlannedDate != null)
                {
                    //临时对策责任人
                    //var TcResponsible = await _repository.Context.Queryable<UserEntity>().Where(it => it.Id == input.TcResponsible).FirstAsync();
                    //长期对策责任人
                    var LcResponsible = await _repository.Context.Queryable<UserEntity>().Where(it => it.Id == input.LcResponsible).FirstAsync();
                    //发送人，拼接字符串
                    //string userlist = TcResponsible.Id + "," + LcResponsible.Id;
                    JArray jArray = new JArray();
                    JObject jObject = new JObject();
                    jObject.Add("text", "客诉-" + input.CustomerName + "-" + input.ProductName + "-" + input.DefectCategory);
                    jObject.Add("no", input.No);
                    jObject.Add("problemAttribution", input.ProblemAttribution);
                    jObject.Add("feedbackStage", input.FeedbackDate);
                    jObject.Add("feedbackUserName", input.FeedbackUserName);
                    jObject.Add("feedbackDate", input.FeedbackDate);
                    jObject.Add("feedbackWay", input.FeedbackWay);
                    jObject.Add("feedbackNo", input.FeedbackNo);
                    jObject.Add("complaintType", input.ComplaintType);
                    jObject.Add("problemDescription", input.ProblemDescription);
                    jObject.Add("checkUserId", input.CheckUserId);
                    jObject.Add("checkDate", input.CheckDate);
                    jObject.Add("checkCause", input.CheckCause);
                    jObject.Add("checkCauseOut", input.CheckCauseOut);
                    jObject.Add("checkCauseRoot", input.CheckCauseRoot);
                    jObject.Add("checkProblem", input.CheckProblem);
                    jObject.Add("checkDuplicate", input.CheckDuplicate);
                    jObject.Add("checkMajor", input.CheckMajor);
                    jObject.Add("checkBadNum", input.CheckBadNum);
                    jObject.Add("creatorUserId", input.CreatorUserId);
                    jObject.Add("creatorTime", customerid.CreatorTine);
                    //jObject.Add("date", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    jArray.Add(jObject);
                    _messageService.AddMessageEvent("CustomerCountermeasure", LcResponsible.Id, jArray.ToJsonString(), null, isLogin);
                    //修改状态为已发送
                    await _repository.Context.Updateable<QmsBusiCustomerComplaintEntity>().SetColumns(it => new QmsBusiCustomerComplaintEntity { IsLongtime = 1 }).Where(it => it.Id == customerid.Id).ExecuteCommandAsync();
                }
                //邮件3触发条件--质量损失填写完毕
                if (!string.IsNullOrEmpty(input.QualityDept) && !string.IsNullOrEmpty(input.QualityResponsible) && !string.IsNullOrEmpty(input.QualityManager) && !string.IsNullOrEmpty(input.QualityMaterial.ToString()) && !string.IsNullOrEmpty(input.QualityRework.ToString()) && !string.IsNullOrEmpty(input.QualityFreight.ToString()) && !string.IsNullOrEmpty(input.QualityTravel.ToString()) && !string.IsNullOrEmpty(input.QualityCDeductions.ToString()) && !string.IsNullOrEmpty(input.QualityEstimated.ToString()) && !string.IsNullOrEmpty(input.QualityTotalAmount.ToString()) && !string.IsNullOrEmpty(input.MassLossRemark))
                {
                    //质量损失责任人
                    var userInfo = await _repository.Context.Queryable<UserEntity>().Where(it => it.Id == input.QualityResponsible).FirstAsync();
                    JArray jArray = new JArray();
                    JObject jObject = new JObject();
                    jObject.Add("text", "客诉-" + input.CustomerName + "-" + input.ProductName + "-" + input.DefectCategory);
                    jObject.Add("no", input.No);
                    jObject.Add("problemAttribution", input.ProblemAttribution);
                    jObject.Add("feedbackStage", input.FeedbackDate);
                    jObject.Add("feedbackUserName", input.FeedbackUserName);
                    jObject.Add("feedbackDate", input.FeedbackDate);
                    jObject.Add("feedbackWay", input.FeedbackWay);
                    jObject.Add("feedbackNo", input.FeedbackNo);
                    jObject.Add("complaintType", input.ComplaintType);
                    jObject.Add("problemDescription", input.ProblemDescription);
                    jObject.Add("checkUserId", input.CheckUserId);
                    jObject.Add("checkDate", input.CheckDate);
                    jObject.Add("checkCause", input.CheckCause);
                    jObject.Add("checkCauseOut", input.CheckCauseOut);
                    jObject.Add("checkCauseRoot", input.CheckCauseRoot);
                    jObject.Add("checkProblem", input.CheckProblem);
                    jObject.Add("checkMajor", input.CheckMajor);
                    jObject.Add("checkBadNum", input.CheckBadNum);
                    //责任部门
                    jObject.Add("qualityDept", input.QualityDept);
                    jObject.Add("qualityResponsible", input.QualityResponsible);
                    jObject.Add("qualityManager", input.QualityManager);
                    jObject.Add("qualityMaterial", input.QualityMaterial);
                    jObject.Add("qualityRework", input.QualityRework);
                    jObject.Add("qualityFreight", input.QualityFreight);
                    jObject.Add("qualityTravel", input.QualityTravel);
                    jObject.Add("qualityCDeductions", input.QualityCDeductions);
                    jObject.Add("qualityEstimated", input.QualityEstimated);
                    jObject.Add("qualityTotalAmount", input.QualityTotalAmount);
                    jObject.Add("remark", input.MassLossRemark);
                    jObject.Add("creatorUserId", input.CreatorUserId);
                    jObject.Add("creatorTime", customerid.CreatorTine);
                    jArray.Add(jObject);
                    _messageService.AddMessageEvent("CustomerMassLoss", userInfo.Id, jArray.ToJsonString(), null, isLogin);
                    //修改状态为已发送
                    await _repository.Context.Updateable<QmsBusiCustomerComplaintEntity>().SetColumns(it => new QmsBusiCustomerComplaintEntity { IsQuality = 1 }).Where(it => it.Id == customerid.Id).ExecuteCommandAsync();
                }
            }
            catch (Exception ex)
            {
                _db.RollbackTran();
                throw Oops.Oh("错误信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 更新客户投诉主表.
        /// </summary>
        /// <param name="id">主键值.</param>
        /// <param name="input">参数.</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] QmsBusiCustomerComplaintUpInput input)
        {
            var customercomplaint = input.Adapt<QmsBusiCustomerComplaintCrInput>();
            var customercomplaintmodel = customercomplaint.Adapt<QmsBUsiCustomerComplaintModel>();
            var entity = input.Adapt<QmsBusiCustomerComplaintEntity>();
            customercomplaintmodel.Id = entity.Id;
            var isOk = await _repository.Context.Updateable(entity).UpdateColumns(it => new
            {
                it.No,
                it.CustomerNo,
                it.CustomerName,
                it.FeedbackStage,
                it.FeedbackUserName,
                it.FeedbackDate,
                it.FeedbackWay,
                it.FeedbackNo,
                it.ComplaintType,
                it.ProductName,
                it.DefectCategory,
                it.ProblemDescription,
                it.CheckUserId,
                it.CheckDate,
                it.CheckCause,
                it.CheckCauseOut,
                it.CheckCauseRoot,
                it.CheckProblem,
                it.CheckDuplicate,
                it.CheckMajor,
                it.TcProcessing,
                it.TcIntercept,
                it.TcPlannedDate,
                it.TcResponsible,
                it.LcPrevention,
                it.LcLeakage,
                it.LcPlannedDate,
                it.LcResponsible,
                it.LcActualDate,
                it.LcStatus,
                it.QualityManager,
                it.QualityMaterial,
                it.QualityRework,
                it.QualityFreight,
                it.QualityTravel,
                it.QualityCDeductions,
                it.QualityEstimated,
                it.QualityTotalAmount,
                it.Remark,
                it.CancelUserId,
                it.CancelDate,
                it.Status,
                it.TcActualDate,
                it.QualityDept,
                it.QualityResponsible,
                it.TcStatus,
                it.ProblemAttribution
            }).ExecuteCommandAsync();
            await UpdateCustomerComplaintStatus(customercomplaintmodel);

            var customerid = _repository.Context.Queryable<QmsBusiCustomerComplaintEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.Id == id).Select(it => new { Id = it.Id, IsInvestigation = it.IsInvestigation, CreatorTine = it.CreatorTime, IsTemporary = it.IsTemporary, IsQuality = it.IsQuality,IsLongtime=it.IsLongtime }).First();
            bool isLogin = true;
            if ((customerid.IsInvestigation == 0 || customerid.IsInvestigation == null) && !string.IsNullOrEmpty(input.CheckUserId))
            {
                var userInfo = await _repository.Context.Queryable<UserEntity>().Where(it => it.Id == input.CheckUserId).FirstAsync();
                JArray jArray = new JArray();
                JObject jObject = new JObject();
                //jObject.Add("text", "客诉-客户名称-产品名称-缺陷类别");
                jObject.Add("text", "客诉-" + input.CustomerName + "-" + input.ProductName + "-" + input.DefectCategory);
                jObject.Add("no", input.No);
                jObject.Add("problemAttribution", input.ProblemAttribution);
                jObject.Add("feedbackStage", input.FeedbackDate);
                jObject.Add("feedbackUserName", input.FeedbackUserName);
                jObject.Add("feedbackDate", input.FeedbackDate);
                jObject.Add("feedbackWay", input.FeedbackWay);
                jObject.Add("feedbackNo", input.FeedbackNo);
                jObject.Add("complaintType", input.ComplaintType);
                jObject.Add("problemDescription", input.ProblemDescription);
                jObject.Add("creatorUserId", input.CreatorUserId);
                jObject.Add("creatorTime", customerid.CreatorTine);
                //jObject.Add("date", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                jArray.Add(jObject);
                _messageService.AddMessageEvent("CustomerBasicInformation", userInfo.Id, jArray.ToJsonString(), null, isLogin);
                //修改状态为已发送
                await _repository.Context.Updateable<QmsBusiCustomerComplaintEntity>().SetColumns(it => new QmsBusiCustomerComplaintEntity { IsInvestigation = 1 }).Where(it => it.Id == customerid.Id).ExecuteCommandAsync();
            }
            //邮件2触发条件--临时对策和长期对策的责任热和计划日期不为空
            if ((customerid.IsTemporary == 0 || customerid.IsTemporary == null) && !string.IsNullOrEmpty(input.TcResponsible) && input.TcPlannedDate != null)
            {
                //临时对策责任人
                var TcResponsible = await _repository.Context.Queryable<UserEntity>().Where(it => it.Id == input.TcResponsible).FirstAsync();
                ////长期对策责任人
                //var LcResponsible = await _repository.Context.Queryable<UserEntity>().Where(it => it.Id == input.LcResponsible).FirstAsync();
                ////发送人，拼接字符串
                //string userlist = TcResponsible.Id + "," + LcResponsible.Id;
                JArray jArray = new JArray();
                JObject jObject = new JObject();
                jObject.Add("text", "客诉-" + input.CustomerName + "-" + input.ProductName + "-" + input.DefectCategory);
                jObject.Add("no", input.No);
                jObject.Add("problemAttribution", input.ProblemAttribution);
                jObject.Add("feedbackStage", input.FeedbackDate);
                jObject.Add("feedbackUserName", input.FeedbackUserName);
                jObject.Add("feedbackDate", input.FeedbackDate);
                jObject.Add("feedbackWay", input.FeedbackWay);
                jObject.Add("feedbackNo", input.FeedbackNo);
                jObject.Add("complaintType", input.ComplaintType);
                jObject.Add("problemDescription", input.ProblemDescription);
                jObject.Add("checkUserId", input.CheckUserId);
                jObject.Add("checkDate", input.CheckDate);
                jObject.Add("checkCause", input.CheckCause);
                jObject.Add("checkCauseOut", input.CheckCauseOut);
                jObject.Add("checkCauseRoot", input.CheckCauseRoot);
                jObject.Add("checkProblem", input.CheckProblem);
                jObject.Add("checkDuplicate", input.CheckDuplicate);
                jObject.Add("checkMajor", input.CheckMajor);
                jObject.Add("checkBadNum", input.CheckBadNum);
                jObject.Add("creatorUserId", input.CreatorUserId);
                jObject.Add("creatorTime", customerid.CreatorTine);
                //jObject.Add("date", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                jArray.Add(jObject);
                _messageService.AddMessageEvent("CustomerCountermeasure", TcResponsible.Id, jArray.ToJsonString(), null, isLogin);
                //修改状态为已发送
                await _repository.Context.Updateable<QmsBusiCustomerComplaintEntity>().SetColumns(it => new QmsBusiCustomerComplaintEntity { IsTemporary = 1 }).Where(it => it.Id == customerid.Id).ExecuteCommandAsync();
            }
            //邮件2触发条件长期对策责任人和计划日期不为空
            if ((customerid.IsLongtime == 0 || customerid.IsLongtime == null) && !string.IsNullOrEmpty(input.LcResponsible) && input.LcPlannedDate != null)
            {
                //临时对策责任人
                //var TcResponsible = await _repository.Context.Queryable<UserEntity>().Where(it => it.Id == input.TcResponsible).FirstAsync();
                //长期对策责任人
                var LcResponsible = await _repository.Context.Queryable<UserEntity>().Where(it => it.Id == input.LcResponsible).FirstAsync();
                ////发送人，拼接字符串
                //string userlist = TcResponsible.Id + "," + LcResponsible.Id;
                JArray jArray = new JArray();
                JObject jObject = new JObject();
                jObject.Add("text", "客诉-" + input.CustomerName + "-" + input.ProductName + "-" + input.DefectCategory);
                jObject.Add("no", input.No);
                jObject.Add("problemAttribution", input.ProblemAttribution);
                jObject.Add("feedbackStage", input.FeedbackDate);
                jObject.Add("feedbackUserName", input.FeedbackUserName);
                jObject.Add("feedbackDate", input.FeedbackDate);
                jObject.Add("feedbackWay", input.FeedbackWay);
                jObject.Add("feedbackNo", input.FeedbackNo);
                jObject.Add("complaintType", input.ComplaintType);
                jObject.Add("problemDescription", input.ProblemDescription);
                jObject.Add("checkUserId", input.CheckUserId);
                jObject.Add("checkDate", input.CheckDate);
                jObject.Add("checkCause", input.CheckCause);
                jObject.Add("checkCauseOut", input.CheckCauseOut);
                jObject.Add("checkCauseRoot", input.CheckCauseRoot);
                jObject.Add("checkProblem", input.CheckProblem);
                jObject.Add("checkDuplicate", input.CheckDuplicate);
                jObject.Add("checkMajor", input.CheckMajor);
                jObject.Add("checkBadNum", input.CheckBadNum);
                jObject.Add("creatorUserId", input.CreatorUserId);
                jObject.Add("creatorTime", customerid.CreatorTine);
                //jObject.Add("date", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                jArray.Add(jObject);
                _messageService.AddMessageEvent("CustomerCountermeasure", LcResponsible.Id, jArray.ToJsonString(), null, isLogin);
                //修改状态为已发送
                await _repository.Context.Updateable<QmsBusiCustomerComplaintEntity>().SetColumns(it => new QmsBusiCustomerComplaintEntity { IsLongtime = 1 }).Where(it => it.Id == customerid.Id).ExecuteCommandAsync();
            }
            //邮件3触发条件--质量损失填写完毕
            if (!string.IsNullOrEmpty(input.QualityDept) && !string.IsNullOrEmpty(input.QualityResponsible) && !string.IsNullOrEmpty(input.QualityManager) && !string.IsNullOrEmpty(input.QualityMaterial.ToString()) && !string.IsNullOrEmpty(input.QualityRework.ToString()) && !string.IsNullOrEmpty(input.QualityFreight.ToString()) && !string.IsNullOrEmpty(input.QualityTravel.ToString()) && !string.IsNullOrEmpty(input.QualityCDeductions.ToString()) && !string.IsNullOrEmpty(input.QualityEstimated.ToString()) && !string.IsNullOrEmpty(input.QualityTotalAmount.ToString()) && !string.IsNullOrEmpty(input.MassLossRemark))
            {
                //质量损失责任人
                var userInfo = await _repository.Context.Queryable<UserEntity>().Where(it => it.Id == input.QualityResponsible).FirstAsync();
                JArray jArray = new JArray();
                JObject jObject = new JObject();
                jObject.Add("text", "客诉-" + input.CustomerName + "-" + input.ProductName + "-" + input.DefectCategory);
                jObject.Add("no", input.No);
                jObject.Add("problemAttribution", input.ProblemAttribution);
                jObject.Add("feedbackStage", input.FeedbackDate);
                jObject.Add("feedbackUserName", input.FeedbackUserName);
                jObject.Add("feedbackDate", input.FeedbackDate);
                jObject.Add("feedbackWay", input.FeedbackWay);
                jObject.Add("feedbackNo", input.FeedbackNo);
                jObject.Add("complaintType", input.ComplaintType);
                jObject.Add("problemDescription", input.ProblemDescription);
                jObject.Add("checkUserId", input.CheckUserId);
                jObject.Add("checkDate", input.CheckDate);
                jObject.Add("checkCause", input.CheckCause);
                jObject.Add("checkCauseOut", input.CheckCauseOut);
                jObject.Add("checkCauseRoot", input.CheckCauseRoot);
                jObject.Add("checkProblem", input.CheckProblem);
                jObject.Add("checkMajor", input.CheckMajor);
                jObject.Add("checkBadNum", input.CheckBadNum);
                //责任部门
                jObject.Add("qualityDept", input.QualityDept);
                jObject.Add("qualityResponsible", input.QualityResponsible);
                jObject.Add("qualityManager", input.QualityManager);
                jObject.Add("qualityMaterial", input.QualityMaterial);
                jObject.Add("qualityRework", input.QualityRework);
                jObject.Add("qualityFreight", input.QualityFreight);
                jObject.Add("qualityTravel", input.QualityTravel);
                jObject.Add("qualityCDeductions", input.QualityCDeductions);
                jObject.Add("qualityEstimated", input.QualityEstimated);
                jObject.Add("qualityTotalAmount", input.QualityTotalAmount);
                jObject.Add("remark", input.MassLossRemark);
                jObject.Add("creatorUserId", input.CreatorUserId);
                jObject.Add("creatorTime", customerid.CreatorTine);
                jArray.Add(jObject);
                _messageService.AddMessageEvent("CustomerMassLoss", userInfo.Id, jArray.ToJsonString(), null, isLogin);
                //修改状态为已发送
                await _repository.Context.Updateable<QmsBusiCustomerComplaintEntity>().SetColumns(it => new QmsBusiCustomerComplaintEntity { IsQuality = 1 }).Where(it => it.Id == customerid.Id).ExecuteCommandAsync();
            }
            if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1001);
        }

        /// <summary>
        /// 批量删除客户投诉主表.
        /// </summary>
        /// <param name="ids">主键数组.</param>
        /// <returns></returns>
        [HttpPost("batchRemove")]
        public async Task BatchRemove([FromBody] List<string> ids)
        {
            var entitys = await _repository.Context.Queryable<QmsBusiCustomerComplaintEntity>().In(it => it.Id, ids).ToListAsync();
            if (entitys.Count > 0)
            {
                try
                {
                    // 开启事务
                    _db.BeginTran();

                    // 批量删除客户投诉主表
                    var isOk = await _repository.Context.Updateable<QmsBusiCustomerComplaintEntity>().SetColumns(it => new QmsBusiCustomerComplaintEntity() { DeleteMark = 1, DeleteTime = DateTime.Now, DeleteUserId = _userManager.UserId }).Where(it => ids.Contains(it.Id)).ExecuteCommandAsync();
                    if (!(isOk > 0))
                    {
                        _db.RollbackTran();
                        throw Oops.Oh("批量删除失败！");
                    }

                    // 关闭事务
                    _db.CommitTran();
                }
                catch (Exception)
                {
                    // 回滚事务
                    _db.RollbackTran();

                    throw Oops.Oh(ErrorCode.COM1002);
                }
            }
        }

        /// <summary>
        /// 客诉主表状态修改.
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("UpdateCustomerComplaintStatus")]
        public async Task UpdateCustomerComplaintStatus(QmsBUsiCustomerComplaintModel input)
        {
            //基础信息填写完成修改状态为"待处理"
            if (!string.IsNullOrEmpty(input.No) && !string.IsNullOrEmpty(input.CustomerNo) && !string.IsNullOrEmpty(input.CustomerName) && !string.IsNullOrEmpty(input.FeedbackStage) && !string.IsNullOrEmpty(input.FeedbackUserName) && !string.IsNullOrEmpty(input.FeedbackDate.ToString()) && !string.IsNullOrEmpty(input.FeedbackWay) && !string.IsNullOrEmpty(input.FeedbackNo) && !string.IsNullOrEmpty(input.ComplaintType) && !string.IsNullOrEmpty(input.ProductName) && !string.IsNullOrEmpty(input.DefectCategory) && !string.IsNullOrEmpty(input.ProblemDescription) && !string.IsNullOrEmpty(input.ProblemAttribution) && !string.IsNullOrEmpty(input.CreatorUserId) && string.IsNullOrEmpty(input.CheckCause)/* && (input.TcStatus == 2 || input.TcStatus == null) && (input.LcStatus == 2 || input.LcStatus == null)*/)
            {
                var isOk1 = _repository.Context.Updateable<QmsBusiCustomerComplaintEntity>().SetColumns(it => new QmsBusiCustomerComplaintEntity() { Status = 0 }).Where(it => it.Id == input.Id).ExecuteCommand();
                if (!(isOk1 > 0))
                    throw Oops.Oh("修改状态失败！");
            }
            //发生原因填写完成修改状态为"处理中"
            if (!string.IsNullOrEmpty(input.CheckCause) && (input.TcStatus == 2 || input.TcStatus == null) && (input.LcStatus == 2 || input.LcStatus == null))
            {
                var isOk2 = await _repository.Context.Updateable<QmsBusiCustomerComplaintEntity>().SetColumns(it => new QmsBusiCustomerComplaintEntity() { Status = 1 }).Where(it => it.Id == input.Id).ExecuteCommandAsync();
                if (!(isOk2 > 0))
                    throw Oops.Oh("修改状态失败！");
            }
            //临时对策关闭"已反馈"
            if (!string.IsNullOrEmpty(input.CheckCause) && input.TcStatus == 1 && (input.LcStatus == 2 || input.LcStatus == null))
            {
                var isOk3 = await _repository.Context.Updateable<QmsBusiCustomerComplaintEntity>().SetColumns(it => new QmsBusiCustomerComplaintEntity() { Status = 2 }).Where(it => it.Id == input.Id).ExecuteCommandAsync();
                if (!(isOk3 > 0))
                    throw Oops.Oh("修改状态失败！");
            }
            //长期对策关闭"已完成"
            if (!string.IsNullOrEmpty(input.CheckCause) && input.LcStatus == 1 && input.TcStatus == 1)
            {
                var isOk4 = await _repository.Context.Updateable<QmsBusiCustomerComplaintEntity>().SetColumns(it => new QmsBusiCustomerComplaintEntity() { Status = 3 }).Where(it => it.Id == input.Id).ExecuteCommandAsync();
                if (!(isOk4 > 0))
                    throw Oops.Oh("修改状态失败！");
            }
        }

        /// <summary>
        /// 生成工单条码.
        /// </summary>
        /// <returns></returns>
        [HttpPost("CreateWorkerCode")]
        public async Task<dynamic> CreateWorkerCode()
        {
            var workordercode = await _billRullService.GetBillNumber("workordeCode");
            return workordercode;
        }

        #region 暂未用到

        /// <summary>
        /// 删除客户投诉主表.
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var isOk = await _repository.Context.Updateable<QmsBusiCustomerComplaintEntity>().SetColumns(it => new QmsBusiCustomerComplaintEntity() { DeleteMark = 1, DeleteTime = DateTime.Now, DeleteUserId = _userManager.UserId }).Where(it => it.Id.Equals(id)).ExecuteCommandAsync();
            if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1002);
        }
        #endregion

    }
}
